﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using StockTradTest.Data;
using StockTradTest;
using System.Threading.Tasks;

namespace TestGraphic
{
    public partial class Form4 : Form
    {
        const double stepPersent = 0.15f;


        Graphics graphics;
        readonly Brush brush;

        //鼠标按下时候的位置记录
        Point mouseDownPoint = Point.Empty;
        bool LMouseDown = false;
        //显示的开始位置
        int showStartCount = 0;

        //记录的
        int oldShowStartCount = 0;
        //绘图用缓存
        Bitmap bmp;
        //窗口处于处理阶段
        public static bool inFocus = true;
        readonly Form2 textForm;
        List<Investor> investors = null;
        //线的x坐标
        int lineX = -1;
        public Form4()
        {
            brush = new SolidBrush(Color.DarkGray);
            InitializeComponent();
            Init();
            textForm = new Form2();
            textForm.MouseMove += new System.Windows.Forms.MouseEventHandler(this.Form4_MouseMove);
            textForm.m_Label.MouseMove += new System.Windows.Forms.MouseEventHandler(this.Form4_MouseMove);
            //textForm.label_Text.MouseMove += new System.Windows.Forms.MouseEventHandler(this.Form1_MouseMove);
            textForm.Visible = false;
        }
        void Init()
        {
            bmp = new Bitmap(this.Width, this.Height);
            graphics = Graphics.FromImage(bmp);
        }
        private async void button_generate_ClickAsync(object sender, EventArgs e)
        {
            if(await RunOnceAsync())
            {
                DrawAliveInvestor(0);
            }

        }

        private void Form4_Load(object sender, EventArgs e)
        {

            Clear();
        }
        private void Clear()
        {
            graphics.Clear(Color.WhiteSmoke);
            graphics.FillRectangle(brush, new RectangleF(0, 0, this.Width - 20, (int)(this.Height * stepPersent)));
            graphics.FillRectangle(brush, new RectangleF(0, (int)(Height * stepPersent) + 5, this.Width - 20, (int)(this.Height * stepPersent)));
        }
        protected override void OnPaint(PaintEventArgs e)
        {
            this.CreateGraphics().DrawImage(bmp, 0, 0);

        }
        private async Task<bool> RunOnceAsync()
        {
            if (investors == null)
            {
                investors = Base.InvestorDatabase.GetInvestorAsync().Result;
                label_log.Text = "暂无数据";
            }
            if (investors == null || investors.Count < 1)
            {
                label_log.Text = "更新数据中";
                await GetInvestor.AutoSaveInvestorsAsync();
                label_log.Text = "存储数据完成";
                investors = Base.InvestorDatabase.GetInvestorAsync().Result;
            }
            if (investors == null || investors.Count < 1)
            {
                label_log.Text = "获取数据失败";
                return false;
            }
            label_log.Text = "获取数据完成";
            return true;
        }
        /// <summary>
        /// 第一幅图绘制期末投资者数量
        /// </summary>
        /// <param name="startCount">开始数据</param>
        private void DrawNewInvestor(int startCount = 0)
        {
            int heightLength = (int)(Height * stepPersent) - 5;
            int widthLength = Width - 20;
            //MessageBox.Show(data[29].ToString());

            if (investors == null) return;
            int maxCount = investors.Count;
            int showCount = (int)Math.Floor(widthLength / 5f);
            if (startCount + showCount > maxCount) startCount = Math.Max(maxCount - showCount - 1, 0);
            double maxNum = 0;
            for (int i = 0; i < Math.Min(showCount + startCount, maxCount); i++)
            {
                maxNum = Math.Max(investors[i].newInvestors, maxNum);
            }
            List<Point> points = new List<Point>();
            for (int i = 0; i < Math.Min(showCount + startCount, maxCount); i++)
            {
                points.Add(new Point(i * 5 + 4, 5 + (int)((1 - investors[i].newInvestors / maxNum) * heightLength)));
                graphics.DrawLine(new Pen(Color.LightGreen, 3),
                    new Point(i * 5 + 4, 5 + (int)((1 - investors[i].newInvestors / maxNum) * heightLength)),
                    new Point(i * 5 + 4, 5 + heightLength));
            }
        }
        private void DrawAliveInvestor(int startCount = 0)
        {
            int heightLength = (int)(Height * stepPersent) - 5;
            int widthLength = Width - 20;
            //MessageBox.Show(data[29].ToString());

            if (investors == null) return;
            int maxCount = investors.Count;
            int showCount = (int)Math.Floor(widthLength / 5f);
            if (startCount + showCount > maxCount) startCount = Math.Max(maxCount - showCount - 1, 0);
            double maxNum = 0;
            for (int i = 0; i < Math.Min(showCount + startCount, maxCount); i++)
            {
                maxNum = Math.Max(investors[i].aliveInvestors, maxNum);
            }
            List<Point> points = new List<Point>();
            for (int i = 0; i < Math.Min(showCount + startCount, maxCount); i++)
            {
                points.Add(new Point(i * 5 + 4, 10 + heightLength + (int)((1 - investors[i].aliveInvestors / maxNum) * heightLength)));
                graphics.DrawLine(new Pen(Color.LightGreen, 3),
                    new Point(i * 5 + 4, 15 + heightLength + (int)((1 - investors[i].aliveInvestors / maxNum) * heightLength)),
                    new Point(i * 5 + 4, 15 + heightLength * 2));
            }
        }
        private void DrawAll(int startCount = 0)
        {
            DrawNewInvestor(startCount);
            DrawAliveInvestor(startCount);
        }
        private void Form4_MouseDown(object sender, MouseEventArgs e)
        {
            textForm.Visible = false;
            if (e.Button == MouseButtons.Left)
            {
                Cursor = Cursors.Hand;

                if (LMouseDown == false)
                {
                    mouseDownPoint = new Point(-e.X, -e.Y);
                    LMouseDown = true;
                    oldShowStartCount = showStartCount;
                    return;
                }
            }
        }

        private void Form4_MouseUp(object sender, MouseEventArgs e)
        {
            LMouseDown = false;
            Cursor = Cursors.Default;
            oldShowStartCount = showStartCount;
        }

        private void Form4_MouseMove(object sender, MouseEventArgs e)
        {
            if (!inFocus || investors == null || investors.Count == 0) return;
            if (LMouseDown)
            {
                showStartCount = oldShowStartCount + (-e.X - mouseDownPoint.X) / 5;
                if (showStartCount < 0) showStartCount = 0;
                if (showStartCount != oldShowStartCount)
                {

                    label_log.Text = showStartCount.ToString();
                    Clear();

                    DrawAll(showStartCount);
                    this.CreateGraphics().DrawImage(bmp, 0, 0);
                }
            }
            else
            {

                Point p = this.PointToClient(Cursor.Position);
                if (this.ClientSize.Width > p.X & 0 < p.X & this.ClientSize.Height - 30 > p.Y & 0 < p.Y)
                {
                    if (p.X <= Width * 0.8)
                    {
                        textForm.Location = this.PointToScreen(new Point(Width - textForm.Width - 20, 0));
                    }
                    else
                    {
                        textForm.Location = this.PointToScreen(new Point(0, 0));
                    }
                    int x = (int)((MousePosition.X - this.Location.X) / 5) * 5 - 6;
                    if (lineX != x)
                    {
                        lineX = x;
                        Clear(); 

                        DrawAll(showStartCount);
                        graphics.DrawLine(new Pen(Color.Black, 1), new Point(x, 1), new Point(x, (int)(Height * 0.89)));

                        this.CreateGraphics().DrawImage(bmp, 0, 0);
                        int dateCount = showStartCount + (x - 4) / 5;
                        if (dateCount < 0 || dateCount >= investors.Count) return;
                        Investor data = investors[showStartCount + (x - 4) / 5];
                        string text = string.Format("年月:{0}\n" +
                            "新增投资者:{1}万\n" +
                            "期末投资者:{2}万\n" +
                            "证券只数:{3}\n" +
                            "证券总面值:{4}亿\n" +
                            "证券总市值:{5}亿\n" +
                            "流通市值:{6}亿\n" +
                            "过户总笔:{7}万\n" +
                            "过户总金额:{8}亿\n" +
                            "结算总额元:{9}亿\n" +
                            "结算净额:{10}亿\n",
                            data.Date,
                            data.newInvestors.ToString("F2"),
                            data.aliveInvestors.ToString("F2"),
                            data.stockNumber,
                            data.stockPrice.ToString("F2"),
                            data.stockMarketPrice.ToString("F2"),
                            data.OnSellPrice.ToString("F2"),
                            data.transferNum.ToString("F2"),
                            data.transferPrice.ToString("F2"),
                            data.closeAllPrice.ToString("F2"),
                            data.closeNetPrice.ToString("F2"));
                        textForm.m_Text = text;
                    }


                    if (textForm.Visible == false) textForm.Visible = true;
                }
                else
                {
                    textForm.Visible = false;
                }
            }


        }

        private void Form4_FormClosing(object sender, FormClosingEventArgs e)
        {
            textForm.Close();
        }

        private void Form4_Resize(object sender, EventArgs e)
        {
            Init();
            Clear();
        }

    }
}
